<?php

namespace App\Http\Controllers;


use App\Models\Luck;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 脚本
 */
class ScriptController
{
    function __construct()
    {
        if(!isset($_GET['key']) || $_GET['key'] != 'wfsdaoliao2020060158CvbsjsdpowjsgzzbaaKJslo')
        {
            echo 'error';die;
        }

        ini_set('memory_limit','1024M');
        set_time_limit(600);
    }

    //发送脚本
    public function send()
    { 
        $begin_time = strtotime(config('luck.luck_begin_time'));
        $end_time   = strtotime(config('luck.luck_end_time'));

        if(time() > $end_time)
        {
            return "活动已结束\n";
        }


        //1-没有队列时，获取数据库  其他-没有队列，不获取数据库
        $origin = isset($_GET['origin']) ?  $_GET['origin'] : 1; 

        $html_log = '';
        $log      = '';
        $succ_sum = 0 ;
        $fail_sum = 0 ;
        $tota_sum = 0;

        $has_run = [];  //避免重复
        
        $time1 = microtime(true);
        $run   = 0;

        //循环一分钟
        while ( $run < 59 ) 
        {
            // 数量
            $freq_key = 'ygj2109_luck_send_freq_sum_'.time();
            $freq_sum = Cache::get($freq_key);
            $freq_sum = empty($freq_sum ) ? 0 : (int)$freq_sum ;

            //一分钟不超过1800个 , 每秒不超过30个
            if($freq_sum < 29 )
            {
                $luck_info =(new Luck())->getSend( $origin == 1 ? true : false );
                if( $luck_info )
                {
                    if(!isset($has_run[$luck_info['id']]))
                    {
                        $time_01 = microtime(true);

                        $has_run[$luck_info['id']] = 1; 

                        //缓存记一个
                        $freq_key = 'ygj2109_luck_send_freq_sum_'.time();
                        if( Cache::has($freq_key))
                        {
                            Cache::increment($freq_key,1);
                        }
                        else
                        {
                            Cache::put($freq_key , 1  , 1  ) ;
                        }

                        $api = $this->to_send($luck_info);


                        $time_02 = microtime(true);

                        if($api['code'] == 1000)
                        {
                            //修改状态
                            $status = Luck::query()->where(['id' =>$luck_info['id'] ])->update(['luck_status' => 2,'send_time' =>time() ]);

                            if($status)
                            {
                                $succ_sum ++ ;
                            }
                            else
                            {
                                $log = date('Y-m-d H:i:s').'|【失败】|红包发放|'.$luck_info['user_id'].'|'.$luck_info['openid'].'|'.$luck_info['partner_trade_no'].'|'.$luck_info['luck_key'].'|原因：红包状态更新失败|接口返回：'.json_encode($api).'|'.round(($time_02 - $time_01)*1000,2).'ms|【'.$origin."】\n";

                                $html_log .= $log;
                                $fail_sum ++ ;
                            }
                        }
                        else
                        {
                            $log = date('Y-m-d H:i:s').'【失败】||红包发放|'.$luck_info['user_id'].'|'.$luck_info['openid'].'|'.$luck_info['partner_trade_no'].'|'.$luck_info['luck_key'].'|原因：接口|接口返回：'.json_encode($api).'|'.round(($time_02 - $time_01 )*1000,2).'ms|【'.$origin."】\n";
                            
                            $html_log .= $log;
                            $fail_sum ++ ;


                            $status =  Luck::query()->where(['id' =>$luck_info['id'] ])->update(['luck_status' => 4,'api_info' => json_encode($api)]);

                        }

                        $tota_sum ++;
                    }
                }
                else
                {
                }
            }
            else
            {
                usleep(20000); //20ms
            }
            $time2 = microtime(true);
            $run   = (int) ($time2 - $time1 ) ;
            
        }
        $html_log = "\n--------------------------------------------\n"
                .date('Y-m-d H:i:s').'|红包发放|结果|总数：'.$tota_sum.'|成功：'.$succ_sum.'|失败：'.($tota_sum-$succ_sum)."\n"
                .$html_log;
 
        return $html_log;
    }

    public function test(){
        $luck_info = Luck::query()->where('id',1)->first()->toArray();
        $api = $this->to_send($luck_info);
        var_dump($api);
    }

    public function to_send($luck_info){
        //先判断当前是积分类型还是卡券
        if ($luck_info['mall_id'] == 'P0299'){
            if ($luck_info['type'] ==1){
                //积分
                $method = 'fzapi.crm.MemberBonusAdj';
                $content = [];
                $content['issue_store'] = $luck_info['mall_id'];
                $content['telephone'] = $luck_info['user_tel'];
                $content['bonus_type'] ='A04';
                $content['bonus_adj'] = +100;
                $content['remark'] ='悦购节';
                $time = date('Y-m-d H:i:s');
                $url = config('luck.yhc_url');
                $query = new Requery($method, $content, $time,$url);
                return $query->query($time);
            }
            else{
                //卡券
                $method = 'fzapi.crm.WXGiftcertIssue';
                $content = [];
                $content['member_telephone'] = $luck_info['user_tel'];
                $content['cardid'] = config('luck.luck_code')[$luck_info['luck_key']];
                $content['giftcert_batchno'] = config('luck.luck_code')[$luck_info['luck_key']];
//                $content['cardid'] = 'KQ0000000624';
//                $content['giftcert_batchno'] = 'KQ0000000624';
                $content['source_type'] = 10;
                $content['order_no'] = $luck_info['partner_trade_no'];
                $content['issue_qty'] = 1;
                $content['operator_code'] ='yuegoujie';
                $content['operator_password'] ='yuegoujie0918';
                $time = date('Y-m-d H:i:s');
                $url = config('luck.yhc_url');
                $query = new Requery($method, $content, $time,$url);
                return $query->query($time);
            }
        }else{
            if ($luck_info['type'] ==1){
                //积分
                $method = 'fzapi.crm.MemberBonusAdj';
                $content = [];
                $content['issue_store'] = $luck_info['mall_id'];
                $content['telephone'] = $luck_info['user_tel'];
                $content['bonus_type'] ='A04';
                $content['bonus_adj'] = +100;
                $content['remark'] ='悦购节';
                $time = date('Y-m-d H:i:s');
                $query = new Requery($method,$content,$time);
                return $query->query($time);
            }
            else{
                //卡券
                $method = 'fzapi.crm.WXGiftcertIssue';
                $content = [];
                $content['member_telephone'] = $luck_info['user_tel'];
                $content['cardid'] = config('luck.luck_code')[$luck_info['luck_key']];
                $content['giftcert_batchno'] = config('luck.luck_code')[$luck_info['luck_key']];
//                $content['cardid'] = 'KQ0000000624';
//                $content['giftcert_batchno'] = 'KQ0000000624';
                $content['source_type'] = 10;
                $content['order_no'] = $luck_info['partner_trade_no'];
                $content['issue_qty'] = 1;
                $content['operator_code'] ='yuegoujie';
                $content['operator_password'] ='yuegoujie0918';
                $time = date('Y-m-d H:i:s');
                $query = new Requery($method,$content,$time);
                return $query->query($time);
            }
        }
    }

    public function getThrid(){
        $method = 'fzapi.crm.ThridWayGiftCertInfo';
        $content = [];
        $content['buildingid'] = '10311';
        $time = date('Y-m-d H:i:s');
        $query = new Requery($method,$content,$time);
        return $query->query($time);
    }

}